#include "echoserver.h"
using std::cout;
using std::endl;

EchoServer::EchoServer(muduo::net::EventLoop *loop, const muduo::net::InetAddress &listenAddr)
    : _loop(loop), _server(loop, listenAddr, "EchoServer")
{
    // set callback
    _server.setConnectionCallback(std::bind(&EchoServer::onConnection, this, std::placeholders::_1));
    _server.setMessageCallback(std::bind(&EchoServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}

void EchoServer::start()
{
    _server.start();
}

void EchoServer::onConnection(const muduo::net::TcpConnectionPtr &conn)
{
    // handle connection
    // cout << "EchoServer - " << conn->peerAddress().toIpPort() << " -> "
    //      << conn->localAddress().toIpPort() << " is "
    //      << (conn->connected() ? "UP" : "DOWN") << endl;
}

void EchoServer::onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp time)
{
    // handle message
    muduo::string msg(buf->retrieveAllAsString());
    // cout << conn->name() << " echo " << msg.size() << " bytes, " << "data received at " << time.toString() << endl;
    conn->send(msg);
}
